package com.inossem.warehousestorage_inossem.activity.refund_storage;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.inossem.utils.base.QRCodeUtils;
import com.inossem.utils.base.RegexUtils;
import com.inossem.utils.base.Utils;
import com.inossem.utils.constant.QRCodeConstant;
import com.inossem.utils.listener.NoDoubleClickListener;
import com.inossem.utils.log.LogUtils;
import com.inossem.warehousestorage_inossem.R;
import com.inossem.warehousestorage_inossem.activity.base.BaseActivity;
import com.inossem.warehousestorage_inossem.activity.refund_storage.extra.RefundStorageExtra;
import com.inossem.warehousestorage_inossem.bean.refundStorage.BatchSpecListBean;
import com.inossem.warehousestorage_inossem.bean.refundStorage.RefundStorageNewBatchBean;
import com.inossem.warehousestorage_inossem.bean.refundStorage.RefundStorageReservedOverviewBean;
import com.inossem.warehousestorage_inossem.bean.refundStorage.RefundStorageSaleBatchListBean;
import com.inossem.warehousestorage_inossem.bean.refundStorage.RefundStorageSaleOverviewBean;
import com.inossem.warehousestorage_inossem.dialog.DialogUtils;
import com.inossem.warehousestorage_inossem.listener.GsonBeanListener;
import com.inossem.warehousestorage_inossem.request.refundStorage.RefundStorageReservedNewBatch;
import com.inossem.warehousestorage_inossem.request.refundStorage.RefundStorageReservedSelectBatchRequest;
import com.inossem.warehousestorage_inossem.utils.ActivityUtils;
import com.inossem.warehousestorage_inossem.utils.RefundStorageUtils;
import com.inossem.warehousestorage_inossem.utils.SPUtils;
import com.zhy.android.percent.support.PercentLinearLayout;

import java.util.ArrayList;
import java.util.List;

/**
 * 作者：wsy on 2017/12/26 14:12
 * <p>
 * 邮箱：445979770@qq.com
 *
 * 预留退库物料详情
 */

public class RefundStorageResercedMaterielDetailActivity extends BaseActivity {

    private static final String TYPE_SERIAL = "serial";

    private static final String TYPE_INDEX = "index";

    private TextView title, serialNumber, materielCode, materielDescription, factory, inventoryAddress,
            demandNumber, hadRefundStorageNumber, batchNumber, pageInfo, showAndHide , reservedLineNumber , movingType;

    private EditText refundStorageNumber;

    private Button previous, next;

    private String serialNumberStr, realSerialNumberStr, unit, mMaterielCode , mFactoraCode , mReservedNumber , mRetainDecimal;

    private int index;

    private RefundStorageReservedOverviewBean.ReservedBodyBean.ItemListBean materielItem;

    private PercentLinearLayout batchLayout;

    private List<BatchSpecListBean> batchBeanList;

    @Override
    protected void onCreateImpl(Bundle savedInstanceState) {
        setContentView(R.layout.activity_refund_storage_reserved_materiel_detail);
        initView(RefundStorageResercedMaterielDetailActivity.this);
        initData(RefundStorageResercedMaterielDetailActivity.this);
    }

    private void initView(Activity activity) {
        title = (TextView) activity.findViewById(R.id.headerTitle);

        serialNumber = (TextView) activity.findViewById(R.id.serialNumber);
        materielCode = (TextView) activity.findViewById(R.id.materielCode);
        materielDescription = (TextView) activity.findViewById(R.id.materielDescription);
        factory = (TextView) activity.findViewById(R.id.factory);
        inventoryAddress = (TextView) activity.findViewById(R.id.inventoryAddress);
        demandNumber = (TextView) activity.findViewById(R.id.demandNumber);
//        hadRefundStorageNumber = (TextView) activity.findViewById(R.id.hadRefundStorageNumber);
        batchNumber = (TextView) activity.findViewById(R.id.batchNumber);
        pageInfo = (TextView) activity.findViewById(R.id.pageInfo);
        showAndHide = (TextView) activity.findViewById(R.id.showAndHide);
        refundStorageNumber = (EditText) activity.findViewById(R.id.refundStorageNumber);
        previous = (Button) activity.findViewById(R.id.previous);
        next = (Button) activity.findViewById(R.id.next);
        batchLayout = (PercentLinearLayout) activity.findViewById(R.id.batchLayout);
        reservedLineNumber = (TextView) activity.findViewById(R.id.reservedLineNumber);
        movingType = (TextView) activity.findViewById(R.id.movingType);
    }

    private void initData(BaseActivity activity) {
        title.setText(activity.getResources().getString(R.string.activity_receive_materiel_detail_title));
        ActivityUtils.initBackAndFunction(activity, getResources().getString(R.string.activity_up_frame_commit_back), new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                backAndUpdate(activity);
            }
        });
        refundStorageNumber.setOnFocusChangeListener((View v, boolean hasFocus) -> {
            if (hasFocus) {
                refundStorageNumber.setText("");
            }
        });
        previous.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                if (index > 0) {
                    index--;
                    changeAndUpdate(activity);
                } else {
                    backAndUpdate(activity);
                }
            }
        });
        next.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                if (index < (RefundStorageUtils.getReservedMaterielListSize(activity) - 1)) {
                    index++;
                    changeAndUpdate(activity);
                } else {
                    backAndUpdate(activity);
                }
            }
        });
        showAndHide.setOnClickListener((View v) -> {
            if (batchLayout.getVisibility() == View.GONE) {
                batchLayout.setVisibility(View.VISIBLE);
                ((TextView) v).setText(activity.getResources().getString(R.string.activity_in_storage_receive_materiel_detail_hide_information));
            } else if (batchLayout.getVisibility() == View.VISIBLE) {
                batchLayout.setVisibility(View.GONE);
                ((TextView) v).setText(activity.getResources().getString(R.string.activity_in_storage_receive_materiel_detail_show_information));
            }
        });
        getExtra(activity);
        getIndexBySerial(activity, realSerialNumberStr);
        getData(activity, TYPE_SERIAL);
        setmScanListener((String scanResult, int length) -> {
            mMaterielCode = QRCodeUtils.DecryptQRCode(scanResult);
            int indexTemp = RefundStorageUtils.getReservedIndexByMaterielCode(activity, mMaterielCode);
            if (indexTemp != -1) {
                if (indexTemp != index) {
                    index = indexTemp;
                    changeAndUpdate(activity);
                }
            } else {
                Utils.middleToast(activity, getResources().getString(R.string.activity_in_storage_receive_materiel_detail_not_find) + mMaterielCode + getResources().getString(R.string.activity_in_storage_receive_materiel_detail_materiel));
            }
        }, QRCodeConstant.TYPE_MATERIEL_CODE);
    }

    private void getExtra(Activity activity) {
        serialNumberStr = activity.getIntent().getStringExtra(RefundStorageExtra.SERIAL);
        realSerialNumberStr = activity.getIntent().getStringExtra(RefundStorageExtra.REAL_SERIAL);
        mReservedNumber = activity.getIntent().getStringExtra(RefundStorageExtra.RESERVED_NUMBER);
        LogUtils.i("mSaleNumber ====== " + mReservedNumber);
    }

    private void getIndexBySerial(Context context, String serialNumber) {
        index = RefundStorageUtils.getReservedIndexBySerial(context, serialNumber);
    }

    private void getData(BaseActivity context, String getMaterielInformationFromType) {
        switch (getMaterielInformationFromType) {
            case TYPE_SERIAL:
                materielItem = RefundStorageUtils.getReservedMaterielInformationBySerial(context, realSerialNumberStr);
                break;
            case TYPE_INDEX:
                materielItem = RefundStorageUtils.getReservedMaterielInformationByIndex(context, index);
                break;
        }
        mFactoraCode = materielItem.getFty_code();
        unit = materielItem.getUnit_name();
        serialNumber.setText(serialNumberStr);
        materielCode.setText(materielItem.getMat_code());
        mMaterielCode = materielItem.getMat_code();
        mRetainDecimal = materielItem.getDecimal_place();
        materielDescription.setText(materielItem.getMat_name());
        factory.setText(materielItem.getFty_code() + " - " + materielItem.getFty_name());
        inventoryAddress.setText(materielItem.getLocation_code() + " - " + materielItem.getLocation_name());
        demandNumber.setText(materielItem.getDemand_qty() + unit);
        reservedLineNumber.setText(materielItem.getReserve_rid());
        movingType.setText(materielItem.getMove_type_name());
//        hadRefundStorageNumber.setText(materielItem.getHadRefundStorageNumber() + unit);
        refundStorageNumber.setText(TextUtils.isEmpty(materielItem.getRefundNumber()) ? "" : (materielItem.getRefundNumber() + unit));
        batchNumber.setText(TextUtils.isEmpty(materielItem.getBatch()) ? context.getResources().getString(R.string.activity_refund_storage_sale_materiel_detail_choose_batch_number) : materielItem.getBatch());
        batchLayout.removeAllViews();
        if (!TextUtils.isEmpty(materielItem.getBatch())) {
            if (materielItem.getBatch().equals(getResources().getString(R.string.activity_refund_storage_reserced_materiel_detail_use_the_new_batch))) {
                List<BatchSpecListBean> list = new ArrayList<>();
                list.addAll(materielItem.getBatch_material_spec_list());
                list.addAll(materielItem.getBatch_spec_list());
                initNewBatchInfo(context, list);
            }else {
                initBatchInfo(context, materielItem.getBatchInfoList());
            }

        }
        batchNumber.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                RefundStorageReservedSelectBatchRequest.request(context, materielItem.getMat_code(), materielItem.getFty_code(), new GsonBeanListener<RefundStorageSaleBatchListBean>() {
                    @Override
                    public void onSuccess(RefundStorageSaleBatchListBean bean) {
                        List<RefundStorageSaleBatchListBean.SaleBatchBodyBean> batchList = bean.getBody();
                        if (batchList == null || batchList.isEmpty()) {
                            Utils.middleToast(context, getResources().getString(R.string.activity_in_storage_receive_list_no_message));
                            batchList = new ArrayList<>();
                        }
//                        else {
                            DialogUtils.getRefundStorageSaleBatchDialog(context, batchList, new DialogUtils.RefundStorageSaleBatchNumberListener() {
                                @Override
                                public void onSelect(Dialog dialog, String batchNumberStr, List<RefundStorageSaleBatchListBean.SaleBatchBodyBean.BatchSpecListBean> batchInfoList) {
                                    batchNumber.setText(batchNumberStr);
                                    initBatchInfo(context, batchInfoList);
                                }

                                @Override
                                public void onNewBatch() {
//                                    RefundStorageReservedNewBatch.request(context, mFactoraCode , mMaterielCode , mReservedNumber, new GsonBeanListener<RefundStorageNewBatchBean>() {
//                                        @Override
//                                        public void onSuccess(RefundStorageNewBatchBean bean) {
//                                            DialogUtils.getNewBatchDialog(context , bean , realSerialNumberStr , new DialogUtils.RefundStorageSaleNewBatchNumberListener() {
//                                                @Override
//                                                public void onNewBatch(List<RefundStorageNewBatchBean.DataBean.BatchBean> list) {
//                                                    batchNumber.setText(getResources().getString(R.string.activity_refund_storage_reserced_materiel_detail_use_the_new_batch));
//                                                    batchBeanList = list;
//                                                    initNewBatchInfo(context, list);
//                                                }
//                                            }).show();
//                                        }
//                                    });

                                    List<BatchSpecListBean> list = new ArrayList<>();
                                    list.addAll(materielItem.getBatch_material_spec_list());
                                    list.addAll(materielItem.getBatch_spec_list());
                                    DialogUtils.getNewBatchDialog(context, list, realSerialNumberStr, new DialogUtils.RefundStorageSaleNewBatchNumberListener() {
                                        @Override
                                        public void onNewBatch(List<BatchSpecListBean> list) {
                                            batchNumber.setText(getResources().getString(R.string.activity_refund_storage_reserced_materiel_detail_use_the_new_batch));
                                            batchBeanList = list;
                                            initNewBatchInfo(context, list);
                                        }
                                    }).show();

                                }
                            }).show();
//                        }
                    }
                });
            }
        });

        pageInfo.setText(RefundStorageUtils.getReservedMaterielListSize(context) + " | " + (index + 1));
        if (index <= 0) {
            previous.setText(getResources().getString(R.string.activity_receive_result_back));
        } else {
            previous.setText(getResources().getString(R.string.activity_inventory_item_previous_page));
        }
        if (index >= (RefundStorageUtils.getReservedMaterielListSize(context) - 1)) {
            next.setText(getResources().getString(R.string.activity_receive_result_back));
        } else {
            next.setText(getResources().getString(R.string.activity_inventory_item_next_page));
        }
    }

    //选择的批次信息
    private void initBatchInfo(Context context, List<RefundStorageSaleBatchListBean.SaleBatchBodyBean.BatchSpecListBean> batchInfoList) {
        if (batchInfoList != null && !batchInfoList.isEmpty()) {
            batchLayout.removeAllViews();
            for (int i = 0; i < batchInfoList.size(); i++) {
                RefundStorageSaleBatchListBean.SaleBatchBodyBean.BatchSpecListBean batchInfo = batchInfoList.get(i);
                RefundStorageUtils.createTextView(context, batchLayout, batchInfo.getBatch_spec_name(), batchInfo.getBatch_spec_value());
            }
        }
    }

    //新建批次信息
    private void initNewBatchInfo(Context context, List<BatchSpecListBean> batchInfoList) {
        if (batchInfoList != null && !batchInfoList.isEmpty()) {
            batchLayout.removeAllViews();
            for (int i = 0; i < batchInfoList.size(); i++) {
                BatchSpecListBean batchInfo = batchInfoList.get(i);
                RefundStorageUtils.createTextView(context, batchLayout, batchInfo.getBatch_spec_name(), batchInfo.getBatch_spec_value());
            }
        }
    }

    private void updateInfo(Context context) {
        materielItem.setRefundNumber(refundStorageNumber.getText().toString().replace(materielItem.getUnit_name(), "").trim());
        materielItem.setBatch(batchNumber.getText().toString());
        int batchCount = batchLayout.getChildCount();
        if (!batchNumber.getText().toString().equals(getResources().getString(R.string.activity_refund_storage_reserced_materiel_detail_use_the_new_batch))) {
            List<RefundStorageSaleBatchListBean.SaleBatchBodyBean.BatchSpecListBean> batchInfoList = new ArrayList<>();
            for (int i = 0; i < batchCount; i++) {
                View view = batchLayout.getChildAt(i);
                String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
                String value = ((TextView) view.findViewById(R.id.text)).getText().toString();
                RefundStorageSaleBatchListBean.SaleBatchBodyBean.BatchSpecListBean batchInfo = new RefundStorageSaleBatchListBean.SaleBatchBodyBean.BatchSpecListBean();
                batchInfo.setBatch_spec_name(name);
                batchInfo.setBatch_spec_value(value);
                batchInfoList.add(batchInfo);
            }
            materielItem.setBatchInfoList(batchInfoList);
            materielItem.setBatchList(new ArrayList<>());
        }else {
            if (batchBeanList != null) {
                materielItem.setBatchList(batchBeanList);
                materielItem.setBatchInfoList(new ArrayList<>());
            }

        }
        RefundStorageUtils.updateReservedRefundStorageItem(context, materielItem);
        LogUtils.i("afterSP ============= " + SPUtils.getReservedRefundStorageInformation(context));
    }

    private String check(Context context) {
        String refundStorageNumberStr = refundStorageNumber.getText().toString().replace(materielItem.getUnit_name(), "").trim();
//        if (TextUtils.isEmpty(refundStorageNumberStr)) {
//            return "退库数量不可以为空";
//        }

        if (!TextUtils.isEmpty(refundStorageNumberStr) && !RegexUtils.checkDecimal(refundStorageNumberStr)) {
            return getResources().getString(R.string.activity_refund_storage_picking_materiel_detail_the_number_of_restores_is_illegal);
        }

        if (!TextUtils.isEmpty(refundStorageNumberStr) && RegexUtils.checkZero(refundStorageNumberStr)) {
            return getResources().getString(R.string.activity_refund_storage_picking_materiel_detail_the_number_of_restores_must_be_greater_than_zero);
        }
        if (!TextUtils.isEmpty(refundStorageNumberStr) &&!Utils.checkRetainDecimal(refundStorageNumberStr, mRetainDecimal)) {
//            Utils.middleToast(context, context.getResources().getString(R.string.activity_in_storage_receive_overview_serial) + serialNumber + );
            return String.format(context.getResources().getString(R.string.common_retain_decimal_illegal), TextUtils.isEmpty(mRetainDecimal) ? context.getResources().getString(R.string.common_retain_decimal_unlimited) : mRetainDecimal);
        }

        if (!TextUtils.isEmpty(refundStorageNumberStr)) {
            float maxNumber = Float.parseFloat(materielItem.getDemand_qty());
            float refundStoragetNumberFloat = Float.parseFloat(refundStorageNumberStr);
            if (refundStoragetNumberFloat > maxNumber) {
                return getResources().getString(R.string.activity_refund_storage_picking_materiel_detail_the_number_of_restores_can_not_be_greater_than_the_number_of_outgoing_libraries_minus_the_number_of_restores);
            }
        }

        String batchNumberStr = batchNumber.getText().toString();
        if (context.getResources().getString(R.string.activity_refund_storage_sale_materiel_detail_choose_batch_number).equals(batchNumberStr)) {
            return getResources().getString(R.string.activity_refund_storage_sale_materiel_detail_choose_batch_number);
        }

        return null;
    }

    private void backAndUpdate(Context context) {
        String checkResult = check(context);
        if (checkResult == null) {
            updateInfo(context);
            super.onBackPressed();
        } else {
            DialogUtils.getConfirmDialog(context, checkResult + "\n" + getResources().getString(R.string.activity_change_storage_materiel_detail_whether_to_force_out), new DialogUtils.ConfirmDialogListener() {
                @Override
                public void onConfirm(Dialog dialog) {
                    RefundStorageResercedMaterielDetailActivity.super.onBackPressed();
                }
            }).show();
        }
    }

    private void changeAndUpdate(BaseActivity activity) {
        String checkResult = check(activity);
        if (checkResult == null) {
            updateInfo(activity);
            getData(activity, TYPE_INDEX);
        } else {
            DialogUtils.getConfirmDialog(activity, checkResult + "\n" + getResources().getString(R.string.activity_in_storage_receive_materiel_detail_force_switch), new DialogUtils.ConfirmDialogListener() {
                @Override
                public void onConfirm(Dialog dialog) {
                    dialog.dismiss();
                    getData(activity, TYPE_INDEX);
                }
            }).show();
        }
    }

    @Override
    public void onBackPressed() {
        backAndUpdate(RefundStorageResercedMaterielDetailActivity.this);
    }
}
